package com.lc.luzhengtang.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lc.luzhengtang.BaseApplication;
import com.lc.luzhengtang.R;
import com.lc.luzhengtang.adapter.CollectionListAdapter;
import com.lc.luzhengtang.base.BaseActivity;
import com.lc.luzhengtang.bean.CollectBean;
import com.lc.luzhengtang.bean.CommenBean;
import com.lc.luzhengtang.conn.ConnAddShop;
import com.lc.luzhengtang.conn.ConnCancelCollect;
import com.lc.luzhengtang.conn.ConnCollectList;
import com.lc.luzhengtang.util.LovelyToast;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.Log;
import com.umeng.socialize.utils.ShareBoardlistener;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.scale.ScaleScreenHelperFactory;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/5/4.
 */
public class CollectionActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {


    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    private static final int TOTAL_COUNTER = 18;

    private static final int PAGE_SIZE = 6;

    CollectionListAdapter indexAdapter;
    @BindView(R.id.img_news)
    ImageView imgNews;
    @BindView(R.id.text_title)
    TextView textTitle;

    private int mCurrentCounter = 0;
    private boolean isErr;
    private boolean mLoadMoreEndGone = false;


    private PopupWindow popWindow;
    private TextView etname, tv01, tv02;

    private LinearLayout layout_shoucang;

    //加入购物车
    private LinearLayout layout_jiagouwuche;

    //小时
    private ImageView img_close;

    private List<CollectBean.DataBeanX.DataBean> list_collection;

    String collect_Cancel_id;
    String goodsid;
    public int currentPage = 1;

    String shop_id;

    String price;
    String num;
    private UMShareListener mShareListener;
    private ShareAction mShareAction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collection);
        ButterKnife.bind(this);
        list_collection = new ArrayList<>();
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(Color.rgb(47, 223, 189));
//        rvList.setLayoutManager(new LinearLayoutManager(this));
        initData();
      /*  getData();
        onRefresh();*/

        mShareListener = new CollectionActivity.CustomShareListener(this);
        /*增加自定义按钮的分享面板*/
        mShareAction = new ShareAction(CollectionActivity.this).setDisplayList(
                SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE
        )

                .setShareboardclickCallback(new ShareBoardlistener() {
                    @Override
                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                        if (snsPlatform.mShowWord.equals("umeng_sharebutton_copy")) {
                            Toast.makeText(CollectionActivity.this, "复制文本按钮", Toast.LENGTH_LONG).show();
                        } else if (snsPlatform.mShowWord.equals("umeng_sharebutton_copyurl")) {
                            Toast.makeText(CollectionActivity.this, "复制链接按钮", Toast.LENGTH_LONG).show();

                        } else if (share_media == SHARE_MEDIA.SMS) {
                            new ShareAction(CollectionActivity.this).withText("来自分享面板标题")
                                    .setPlatform(share_media)
                                    .setCallback(mShareListener)
                                    .share();
                        } else {
                            Log.d(collect_Cancel_id, "44444444444444444444444");
                            Log.d(collect_Cancel_id, "44444444444444444444444");
                            UMWeb web = new UMWeb("http://luzhengtang.cn/index.php/mobile/goods/details?id=" + goodsid);
                            web.setTitle("清君堂");
                            web.setDescription("商品详情");
//                            web.setThumb(new UMImage(CollectionActivity.this, R.mipmap.logo));
                            new ShareAction(CollectionActivity.this).withMedia(web)
                                    .setPlatform(share_media)
                                    .setCallback(mShareListener)
                                    .share();

                        }
                    }
                });
    }


    private static class CustomShareListener implements UMShareListener {

        private WeakReference<CollectionActivity> mActivity;

        private CustomShareListener(CollectionActivity activity) {
            mActivity = new WeakReference(activity);
        }

        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {

            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(mActivity.get(), platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                        && platform != SHARE_MEDIA.EMAIL
                        && platform != SHARE_MEDIA.FLICKR
                        && platform != SHARE_MEDIA.FOURSQUARE
                        && platform != SHARE_MEDIA.TUMBLR
                        && platform != SHARE_MEDIA.POCKET
                        && platform != SHARE_MEDIA.PINTEREST

                        && platform != SHARE_MEDIA.INSTAGRAM
                        && platform != SHARE_MEDIA.GOOGLEPLUS
                        && platform != SHARE_MEDIA.YNOTE
                        && platform != SHARE_MEDIA.EVERNOTE) {
//                    Toast.makeText(mActivity.get(), platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
                }

            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                    && platform != SHARE_MEDIA.EMAIL
                    && platform != SHARE_MEDIA.FLICKR
                    && platform != SHARE_MEDIA.FOURSQUARE
                    && platform != SHARE_MEDIA.TUMBLR
                    && platform != SHARE_MEDIA.POCKET
                    && platform != SHARE_MEDIA.PINTEREST

                    && platform != SHARE_MEDIA.INSTAGRAM
                    && platform != SHARE_MEDIA.GOOGLEPLUS
                    && platform != SHARE_MEDIA.YNOTE
                    && platform != SHARE_MEDIA.EVERNOTE) {
//                Toast.makeText(mActivity.get(), platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
                if (t != null) {
                    Log.d("throw", "throw:" + t.getMessage());
                }
            }

        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {

//            Toast.makeText(mActivity.get(), platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    }

    protected void initData() {
        rvList.setItemAnimator(new DefaultItemAnimator());
        //recyclerView.setLayoutManager(new LinearLayoutManager(context));
        rvList.setLayoutManager(new LinearLayoutManager(this));

        indexAdapter = new CollectionListAdapter(null);
        indexAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        indexAdapter.isFirstOnly(false);
        rvList.setAdapter(indexAdapter);

        swipeLayout.setColorSchemeColors(Color.RED, Color.BLUE, Color.GREEN);
        swipeLayout.setOnRefreshListener(this);
        indexAdapter.setOnLoadMoreListener(this);

        //开启loading,获取数据
        setRefreshing(true);

    }


    @Override
    protected void onResume() {
        super.onResume();
        onRefresh();

        indexAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                goodsid = list_collection.get(position).getGoodsId() + "";
                collect_Cancel_id = list_collection.get(position).getId() + "";
                price = list_collection.get(position).getSales();
//                        num=list_collection.get(position).getTitle();
                showPopupWindow(view);
            }
        });
    }

    public void setRefreshing(final boolean refreshing) {
        swipeLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeLayout.setRefreshing(refreshing);
            }
        });
    }


    @Override
    public void onRefresh() {
        new ConnCollectList(BaseApplication.basePreferences.readUid(), String.valueOf(currentPage), new AsyCallBack<CollectBean>() {
            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
                indexAdapter.setEnableLoadMore(false);
            }

            @Override
            public void onSuccess(String toast, int type, Object o, CollectBean collectBean) throws Exception {
                super.onSuccess(toast, type, o, collectBean);
//                list_collection.clear();
//                list_collection.addAll(collectBean.getData().getData());
                list_collection = collectBean.getData().getData();
                if (list_collection != null) {
                    currentPage = 1;
                    indexAdapter.setNewData(list_collection);
                }
                textTitle.setText("我的收藏(" + list_collection.size() + ")");


            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                swipeLayout.setRefreshing(false);
                indexAdapter.setEnableLoadMore(false);
            }
        }

        ).execute(CollectionActivity.this, false);
    }

    @Override
    public void onLoadMoreRequested() {
        new ConnCollectList(BaseApplication.basePreferences.readUid(), String.valueOf(currentPage), new AsyCallBack<CollectBean>() {
            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
                indexAdapter.setEnableLoadMore(true);
            }

            @Override
            public void onSuccess(String toast, int type, Object o, CollectBean collectBean) throws Exception {
                super.onSuccess(toast, type, o, collectBean);

                list_collection = collectBean.getData().getData();
                if (list_collection != null) {
                    currentPage++;
                    indexAdapter.setNewData(list_collection);
                } else {
                    //显示没有更多数据
                    // newsAdapter.loadComplete();
                    indexAdapter.loadMoreComplete();
                    View noDataView = LayoutInflater.from(CollectionActivity.this).inflate(R.layout.item_no_data, (ViewGroup) rvList.getParent(), false);
                    indexAdapter.addFooterView(noDataView);
                }
            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                indexAdapter.setEnableLoadMore(false);
                indexAdapter.removeAllFooterView();
                //最后调用结束刷新的方法
                setRefreshing(false);
            }
        }


        ).execute(CollectionActivity.this, false);
    }

    @OnClick({R.id.img_news})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.img_news:
                finish();
                break;

        }
    }


    private void showPopupWindow(View parent) {
        if (popWindow == null) {
        /*    View view = BoundViewHelper.boundView(this, MyApplication.scaleScreenHelper.loadView((ViewGroup) LayoutInflater.from(this)
                    .inflate(R.layout.pop_select_photo2, null)));*/
//ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) convertView);
//            LayoutInflater.from(this).inflate(R.layout.pop_select_photo2,null)
            View view = ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) LayoutInflater.from(this).inflate(R.layout.pop_collect, null));
            //LayoutParams相当于一个Layout的信息包，它封装了Layout的位置、高、宽等信息。
            popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            initPop(view);
        }
        //设置动画效果
        popWindow.setAnimationStyle(android.R.style.Animation_InputMethod);
        //获取popwindow焦点
        popWindow.setFocusable(true);
        //设置popwindow如果点击外面区域，便关闭。
        popWindow.setOutsideTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        //实现软键盘不自动弹出,ADJUST_RESIZE属性表示Activity的主窗口总是会被调整大小，从而保证软键盘显示空间。
        popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置popwindow显示位置
        popWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    public void initPop(View view) {

        tv02 = (TextView) view.findViewById(R.id.tv_02);//相册
        layout_shoucang = (LinearLayout) view.findViewById(R.id.layout_shoucang);

        layout_shoucang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                cancelCollect();
                onRefresh();
                //取消收藏
                popWindow.dismiss();

            }
        });

        layout_jiagouwuche = (LinearLayout) view.findViewById(R.id.layout_jiagouwuche);
        layout_jiagouwuche.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                new ConnAddShop(goodsid, BaseApplication.basePreferences.readUid(), "1", "盒", price, new AsyCallBack<CommenBean>() {
                    @Override
                    public void onStart(int type) throws Exception {
                        super.onStart(type);
                    }

                    @Override
                    public void onSuccess(String toast, int type, Object o, CommenBean commenBean) throws Exception {
                        super.onSuccess(toast, type, o, commenBean);
                        //  Toast.makeText(getActivity(), "成功加入购物车", Toast.LENGTH_SHORT).show();
                        LovelyToast.makeText(CollectionActivity.this, "成功加入购物车", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                    }

                    @Override
                    public void onFail(String toast, int type) throws Exception {
                        super.onFail(toast, type);
                    }

                    @Override
                    public void onEnd(String toast, int type) throws Exception {
                        super.onEnd(toast, type);
                        //可能需要移除之前添加的布局

                        //最后调用结束刷新的方法
//                        setRefreshing(false);
                    }
                }

                ).execute(CollectionActivity.this, false);

                popWindow.dismiss();
                //startAlbum(mineHeadIv);
            }
        });


        img_close = (ImageView) view.findViewById(R.id.img_close);
        img_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });

        LinearLayout layout_dismiss = (LinearLayout) view.findViewById(R.id.layout_dismiss);
        layout_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        //立即购买
        LinearLayout layout_purchase = (LinearLayout) view.findViewById(R.id.layout_purchase);
        layout_purchase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2 = new Intent();
                intent2.putExtra("cart_id", goodsid);
                intent2.putExtra("num", "1");
                intent2.putExtra("he", "盒");
                intent2.putExtra("bd", price);
                intent2.setClass(CollectionActivity.this, ConfirmOrderActivity2.class);
                startActivity(intent2);
            }
        });

       /* Intent intent2 = new Intent();
        intent2.putExtra("cart_id", shop_id);
        intent2.putExtra("num", num + "");
        intent2.putExtra("he", "盒");
        intent2.setClass(ShopDetailActivity.this, ConfirmOrderActivity3.class);
        startActivity(intent2);*/
//分享
        LinearLayout layout_share = (LinearLayout) view.findViewById(R.id.layout_share);
        layout_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mShareAction.open();
            }
        });

    }


    public void cancelCollect() {
        new ConnCancelCollect(BaseApplication.basePreferences.readUid(), collect_Cancel_id, new AsyCallBack<CommenBean>() {
            @Override
            public void onSuccess(String toast, int type, Object o, CommenBean collectBean) throws Exception {
                super.onSuccess(toast, type, o, collectBean);
                LovelyToast.makeText(CollectionActivity.this, collectBean.getMessage(), 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                LovelyToast.makeText(CollectionActivity.this, "网络访问失败", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);

            }
        }


        ).execute(CollectionActivity.this, false);
    }


}
